package com.rc.adapter;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.rc.activity.R;
import com.rc.activity.dao.tbl_Merchant;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.fragment.ReceiptDetailFragment;
import com.rc.object.MerchantObj;
import com.rc.object.ReceiptObj;
import com.rc.util.Util;

@SuppressLint("SimpleDateFormat")
public class ReceiptListAdapter extends BaseAdapter {

	private FragmentActivity mActivity;
	private ArrayList<ReceiptObj> items;
	public boolean isShowCheck = false;
	private CheckBox cbMulti;
	private int mReceiptType;
	boolean[] checkBoxState;
	private int mReceiptKey;
	private int mCountReceipt;
	private int numberFilter;

	public ReceiptListAdapter(FragmentActivity at, ArrayList<ReceiptObj> item,
			int mReceiptKey, int mCountReceipt, int numberFilter) {
		mActivity = at;
		this.items = item;
		this.mReceiptKey = mReceiptKey;
		checkBoxState = new boolean[item.size()];
		this.mCountReceipt = mCountReceipt;
		this.numberFilter = numberFilter;
	}

	public int getCount() {
		if (items == null) {
			return 0;
		}
		return items.size();
	}

	public Object getItem(int position) {
		return items.get(position);
	}

	public long getItemId(int position) {
		return 0;
	}

	// create a new view for each item referenced by the Adapter
	@SuppressLint("ResourceAsColor")
	public View getView(final int position, View convertView, ViewGroup parent) {
		View v = convertView;
		TextView txtMoney, txtTime, txtNameReceipt, txtReceiptType;

		if (convertView == null) { // if it's not recycled, initialize some
									// attributes
			LayoutInflater vi = (LayoutInflater) mActivity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.receiptlist_itemlist, null);

		}
		cbMulti = (CheckBox) v.findViewById(R.id.cbMulti);
		txtMoney = (TextView) v.findViewById(R.id.txtMoney);
		txtTime = (TextView) v.findViewById(R.id.txtTime);
		txtReceiptType = (TextView) v.findViewById(R.id.txtReceiptType);
		txtNameReceipt = (TextView) v.findViewById(R.id.txtNameReceipt);

		if (!isShowCheck) {
			cbMulti.setVisibility(View.GONE);
		} else {
			cbMulti.setVisibility(View.VISIBLE);
		}

		txtMoney.setText("$" + String.valueOf(items.get(position).getTotal()));

		// Format date
		String strDate = items.get(position).getDateTime();
		txtTime.setText(strDate);
		txtNameReceipt.setText(items.get(position).getMerchantName());
		if (items.get(position).getMerchantID() == 0) {
			txtNameReceipt.setText(mActivity
					.getString(R.string.merchant_unrecognized));
		}
		String ReceiptType = items.get(position).getReceiptType();
		if (ReceiptType != null) {
			mReceiptType = Integer.valueOf(ReceiptType);
			switch (mReceiptType) {
			case 1:
				ReceiptType = mActivity.getString(R.string.digital_receipts);
				break;
			case 2:
				ReceiptType = mActivity.getString(R.string.email_receipts);
				break;
			case 3:
				ReceiptType = mActivity.getString(R.string.paper_receipts);
				break;
			case 4:
				ReceiptType = mActivity.getString(R.string.manual_receipts);
				break;
			default:
				break;
			}
		}
		// items.get(position).setCheckbox(cbMulti.isChecked());
		txtReceiptType.setText(ReceiptType);
		cbMulti.setChecked(items.get(position).isCheckbox());
		v.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isShowCheck) {
					cbMulti = null;
					cbMulti = ((CheckBox) v.findViewById(R.id.cbMulti));
					if (cbMulti.isChecked()) {
						cbMulti.setChecked(false);
						items.get(position).setCheckbox(false);
					} else {
						items.get(position).setCheckbox(true);
						cbMulti.setChecked(true);
					}
				} else {
					// check merchant unrecognize
					// if (items.get(position).getMerchantID() == 0) {
					// showDialog(position);
					// } else {
					// if (items.get(position).getIsOpen() == 0) {
					// updateReceipt(position, items.get(position)
					// .getMerchantID());
					// }
					// Fragment fragment = new ReceiptDetailFragment(items
					// .get(position).getReceiptID(), mReceiptKey,
					// mCountReceipt, numberFilter);
					// Util.pushFragmentReceiptBox(fragment, mActivity, "2");
					// }
					if (items.get(position).getIsOpen() == 0) {
						updateReceipt(position, items.get(position)
								.getMerchantID());
					}
					Fragment fragment = new ReceiptDetailFragment(items.get(
							position).getReceiptID(), mReceiptKey,
							mCountReceipt, numberFilter);
					Util.pushFragmentReceiptBox(fragment, mActivity, "2");
				}
			}
		});
		if (items.get(position).getIsOpen() == 0) {
			txtNameReceipt.setTypeface(null, Typeface.BOLD);
			txtMoney.setTypeface(null, Typeface.BOLD);
			v.setBackgroundResource(R.drawable.background_item);
		} else {
			txtMoney.setTypeface(null, Typeface.NORMAL);
			txtNameReceipt.setTypeface(null, Typeface.NORMAL);
			v.setBackgroundResource(R.drawable.background_item_read);
		}
		v.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				cbMulti.setTag(position);
				return false;
			}
		});
		return v;
	}

	/**
	 * update receipt
	 */

	private boolean updateReceipt(int position, long merchantID) {
		tbl_Receipt objReceipt = new tbl_Receipt();
		objReceipt = DatabaseSupport.getReceiptByID(items.get(position)
				.getReceiptID(), mActivity);
		if (objReceipt.getMerchantID() != merchantID) {
			objReceipt.setMerchantID(merchantID);
		}
		objReceipt.setIsOpened(1);
		objReceipt.setIsUpdate("1");
		// update Receipt
		if (mActivity.getContentResolver().update(
				Contract.CONTENT_URI_RECEIPT,
				objReceipt.getContentValues(),
				tbl_ReceiptDao.Properties.ReceiptID.columnName + " = "
						+ items.get(position).getReceiptID(), null) != -1) {
			return true;
		}

		return false;
	}

	private ArrayList<tbl_Merchant> arrMerchantSearch;
	private boolean isShowList = true;
	private MerChantNameAdapter adpDialog;
	private ArrayList<tbl_Merchant> arrMerchant;

	public ArrayList<tbl_Merchant> searchListView(
			ArrayList<tbl_Merchant> mListView, String contentSearch) {
		ArrayList<tbl_Merchant> arrMerchant = new ArrayList<tbl_Merchant>();
		for (int i = 0; i < mListView.size(); i++) {
			if (mListView.get(i).getName().toUpperCase()
					.contains(contentSearch.toUpperCase())) {
				arrMerchant.add(mListView.get(i));
			}

		}
		return arrMerchant;
	}

	private void showDialog(final int position) {

		final Dialog dialog = new Dialog(mActivity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_create_merchant);
		final ListView lvMerChantName = (ListView) dialog
				.findViewById(R.id.lvMerChantName);
		Cursor cursor = mActivity.getContentResolver().query(
				Contract.CONTENT_URI_MERCHANT, null, null, null, null);
		arrMerchant = new ArrayList<tbl_Merchant>();
		arrMerchant = MerchantObj.getObjectbyCursor(cursor);
		adpDialog = new MerChantNameAdapter(mActivity, arrMerchant, "");
		lvMerChantName.setAdapter(adpDialog);
		final TextView txtMerchantAddress = (TextView) dialog
				.findViewById(R.id.txtMerchantAddress);
		final TextView txtMerchantName = (TextView) dialog
				.findViewById(R.id.txtMerchantName);
		txtMerchantName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (txtMerchantName.getText().toString().length() > 1
						&& !isShowList) {
					arrMerchantSearch = new ArrayList<tbl_Merchant>();
					arrMerchantSearch = searchListView(arrMerchant,
							txtMerchantName.getText().toString());
					adpDialog.notiB(arrMerchantSearch);
					Util.setListViewHeightBasedOnChildren(lvMerChantName);
					if (arrMerchantSearch.size() > 0) {
						lvMerChantName.setVisibility(View.VISIBLE);
					} else {
						lvMerChantName.setVisibility(View.GONE);
					}

					lvMerChantName
							.setOnItemClickListener(new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> parent,
										View view, int position, long id) {
									tbl_Merchant objMerchant = new tbl_Merchant();
									objMerchant = arrMerchantSearch
											.get(position);
									txtMerchantName.setText(objMerchant
											.getName().toString());
									txtMerchantAddress.setText(objMerchant
											.getAddress().toString());
									lvMerChantName.setVisibility(View.GONE);
								}
							});
				} else {
					lvMerChantName.setVisibility(View.GONE);
					isShowList = false;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		((LinearLayout) dialog.findViewById(R.id.llOk))
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						tbl_Merchant objMerchant = new tbl_Merchant();
						objMerchant.setAddress(txtMerchantAddress.getText()
								.toString());
						objMerchant.setName(txtMerchantName.getText()
								.toString());
						objMerchant.setMerchantID(DatabaseSupport
								.insertOrUpdateMerchant(objMerchant, mActivity));
						if (items.get(position).getMerchantID() != objMerchant
								.getMerchantID()) {
							if (updateReceipt(position,
									objMerchant.getMerchantID())) {
								dialog.dismiss();
								Fragment fragment = new ReceiptDetailFragment(
										items.get(position).getReceiptID(),
										mReceiptKey, mCountReceipt,
										numberFilter);
								Util.pushFragmentReceiptBox(fragment,
										mActivity, "2");
							}
						}

					}
				});
		((LinearLayout) dialog.findViewById(R.id.llCancel))
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	public void notiB(ArrayList<ReceiptObj> arrReceiptObj, int mReceiptKey,
			int mCountReceipt, int numberFilter) {
		this.mCountReceipt = mCountReceipt;
		this.numberFilter = numberFilter;
		this.items = arrReceiptObj;
		this.mReceiptKey = mReceiptKey;
		notifyDataSetChanged();
	}

}